// 生成会话ID
const sessionId = 'session_' + Date.now();

// DOM元素
const resultPreview = document.getElementById('result-preview');
const downloadBtn = document.getElementById('download-btn');
const clearBtn = document.getElementById('clear-btn');
const chatHistory = document.getElementById('chat-history');
const messageInput = document.getElementById('message-input');
const sendBtn = document.getElementById('send-btn');
const loading = document.getElementById('loading');

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 确保思考指示器初始状态是隐藏的
    const thinkingIndicator = document.getElementById('ai-thinking');
    if (thinkingIndicator) {
        thinkingIndicator.style.display = 'none';
    }

    // 绑定多文件上传事件
    const imageUpload = document.getElementById('image-upload');
    if (imageUpload) {
        imageUpload.addEventListener('change', function() {
            uploadImages(this.files);
        });
    }

    const clearBtn = document.getElementById('clear-btn');
    const sendBtn = document.getElementById('send-btn');
    const messageInput = document.getElementById('message-input');
    const downloadBtn = document.getElementById('download-btn');
    const clearImagesBtn = document.getElementById('clear-images-btn');

    if (clearBtn) {
        clearBtn.addEventListener('click', clearConversation);
    }

    if (clearImagesBtn) {
        clearImagesBtn.addEventListener('click', clearImages);
    }

    if (sendBtn) {
        sendBtn.addEventListener('click', sendMessage);
    }

    // 按Enter键发送消息
    if (messageInput) {
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    }

    // 初始化下载按钮
    if (downloadBtn) {
        downloadBtn.addEventListener('click', downloadResult);
    }

});

// 全局变量，存储当前图像信息
let currentImages = [];

// 多图像上传函数
function uploadImages(files) {
    if (!files || files.length === 0) return;

    // 创建FormData并添加所有文件
    const formData = new FormData();
    formData.append('session_id', sessionId);

    // 添加所有文件
    for (let i = 0; i < files.length; i++) {
        formData.append('images', files[i]);
    }

    // 清空预览区域并显示上传中的消息
    const previewsContainer = document.getElementById('image-previews');
    previewsContainer.innerHTML = '<span>正在上传图像...</span>';

    fetch('/upload_images', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 将新上传的图像添加到当前图像列表
            data.paths.forEach((path, index) => {
                currentImages.push({
                    path: path,
                    preview: data.previews[index],
                    name: `图像 ${currentImages.length + 1}`
                });
            });

            // 更新预览区域
            updateImagePreviews();

            // 更新图像计数
            document.getElementById('image-count').textContent =
                `当前已上传: ${currentImages.length} 张图像`;
        } else {
            alert('上传失败: ' + data.error);
            // 恢复预览区域
            previewsContainer.innerHTML = '<span>未上传图像</span>';
            document.getElementById('image-count').textContent = '当前已上传: 0 张图像';
        }
    })
    .catch(error => {
        alert('上传出错: ' + error);
        // 恢复预览区域
        previewsContainer.innerHTML = '<span>未上传图像</span>';
        document.getElementById('image-count').textContent = '当前已上传: 0 张图像';
    });
}

// 更新图像预览（包含删除按钮）
function updateImagePreviews() {
    const previewsContainer = document.getElementById('image-previews');
    previewsContainer.innerHTML = '';

    if (currentImages.length === 0) {
        previewsContainer.innerHTML = '<span>未上传图像</span>';
        return;
    }

    currentImages.forEach((image, index) => {
        const imageContainer = document.createElement('div');
        imageContainer.style.display = 'inline-block';
        imageContainer.style.margin = '5px';
        imageContainer.style.position = 'relative';
        imageContainer.style.textAlign = 'center';

        const img = document.createElement('img');
        img.src = image.preview;
        img.alt = image.name;
        img.style.maxWidth = '150px';
        img.style.maxHeight = '150px';
        img.style.border = '1px solid #ddd';
        img.style.borderRadius = '5px';

        const deleteBtn = document.createElement('button');
        deleteBtn.innerHTML = '×';
        deleteBtn.style.position = 'absolute';
        deleteBtn.style.top = '-5px';
        deleteBtn.style.right = '-5px';
        deleteBtn.style.background = '#ff4d4f';
        deleteBtn.style.color = 'white';
        deleteBtn.style.border = 'none';
        deleteBtn.style.borderRadius = '50%';
        deleteBtn.style.width = '20px';
        deleteBtn.style.height = '20px';
        deleteBtn.style.cursor = 'pointer';
        deleteBtn.style.fontSize = '14px';
        deleteBtn.style.lineHeight = '20px'; // 关键修改：与按钮高度相同
        deleteBtn.style.textAlign = 'center'; // 添加水平居中
        deleteBtn.style.padding = '0'; // 确保没有内边距
        deleteBtn.title = '删除此图像';

        // 绑定删除事件
        deleteBtn.onclick = function() {
            deleteImage(index);
        };

        const imageLabel = document.createElement('div');
        imageLabel.textContent = image.name;
        imageLabel.style.fontSize = '14px';
        imageLabel.style.marginTop = '5px';

        imageContainer.appendChild(img);
        imageContainer.appendChild(deleteBtn);
        imageContainer.appendChild(imageLabel);
        previewsContainer.appendChild(imageContainer);
    });
}

// 删除单个图像
function deleteImage(index) {
    if (index < 0 || index >= currentImages.length) return;

    const imageToDelete = currentImages[index];

    // 从当前图像列表中移除
    currentImages.splice(index, 1);

    // 更新预览区域
    updateImagePreviews();

    // 更新图像计数
    document.getElementById('image-count').textContent =
        `当前已上传: ${currentImages.length} 张图像`;

    // 调用后端删除图像文件
    const formData = new FormData();
    formData.append('session_id', sessionId);
    formData.append('image_path', imageToDelete.path);

    fetch('/delete_image', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (!data.success) {
            console.error('删除图像文件失败:', data.error);
        }
    })
    .catch(error => {
        console.error('删除图像请求出错:', error);
    });
}

// 清空所有图像
function clearImages() {
    if (currentImages.length === 0) return;

    // 调用后端删除所有图像文件
    const formData = new FormData();
    formData.append('session_id', sessionId);

    // 发送所有图像路径到后端进行删除
    currentImages.forEach(image => {
        formData.append('image_paths', image.path);
    });

    fetch('/delete_images', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (!data.success) {
            console.error('删除图像文件失败:', data.error);
        }
    })
    .catch(error => {
        console.error('删除图像请求出错:', error);
    });

    // 清空前端图像列表
    currentImages = [];

    // 更新预览区域
    updateImagePreviews();

    // 更新图像计数
    document.getElementById('image-count').textContent = '当前已上传: 0 张图像';
}

// 发送消息（分两步：先获取文字回复，再异步处理图像）
function sendMessage() {
    const message = messageInput.value.trim();
    if (!message) return;

    // 立即显示用户消息
    addMessageToHistory('user', message);
    messageInput.value = '';

    // 显示思考指示器
    showThinking(true);

    const formData = new FormData();
    formData.append('session_id', sessionId);
    formData.append('message', message);

    // 添加当前所有图像路径
    currentImages.forEach(image => {
        formData.append('image_paths', image.path);
    });

    // 第一步：获取文字回复
    fetch('/chat', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // 隐藏思考指示器
        showThinking(false);

        if (data.success) {
            // 立即显示AI文字回复
            addMessageToHistory('assistant', data.response);

            // 如果有工具需要执行，异步执行工具
            if (data.tool_info) {
                // 添加处理中的提示消息
                const processingMessageId = addProcessingMessage(data.tool_info.tool);
                executeToolAsync(data.tool_info, processingMessageId);
            }
        } else {
            alert('发送失败: ' + data.error);
        }
    })
    .catch(error => {
        showThinking(false);
        alert('发送出错: ' + error);
    });
}

// 添加处理中的提示消息
function addProcessingMessage(toolType) {
    const chatHistory = document.getElementById('chat-history');
    const thinkingIndicator = document.getElementById('ai-thinking');

    // 创建处理中消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = 'chat-message system';
    messageDiv.id = 'processing-' + Date.now();

    const toolName = toolType === 'stitch_images' ? '拼接' : '融合';

    messageDiv.innerHTML = `
        <div class="message-header">
            <span>🔄 系统</span>
            <span class="message-time">${new Date().toLocaleTimeString()}</span>
        </div>
        <div class="message-content">
            <div>正在${toolName}图像，这可能需要一些时间...</div>
            <div class="progress-indicator">
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
            </div>
        </div>
    `;

    // 将消息插入到思考指示器之前
    chatHistory.insertBefore(messageDiv, thinkingIndicator);

    // 滚动到对话历史底部
    scrollToChatBottom();

    return messageDiv.id;
}

// 异步执行工具
function executeToolAsync(toolInfo, processingMessageId) {
    const formData = new FormData();
    formData.append('session_id', sessionId);
    formData.append('tool', toolInfo.tool);
    formData.append('tool_input', JSON.stringify(toolInfo.tool_input));

    // 添加图像路径
    toolInfo.image_paths.forEach(path => {
        formData.append('image_paths', path);
    });

    // 第二步：异步执行工具获取图像结果
    fetch('/execute_tool', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // 移除处理中的提示
        removeProcessingMessage(processingMessageId);

        if (data.success) {

            // 如果有处理结果，显示图像
            if (data.result_image) {
                // 保存图像数据到全局变量，供下载使用
                window.lastResultImageData = data.result_image;

                // 显示图像
                resultPreview.innerHTML = `<img src="${data.result_image}" alt="处理结果">`;
                downloadBtn.style.display = 'block';
            }
            else{
                addMessageToHistory('system', `${data.tool_result}`);
            }
        } else {
            // 显示错误信息
            addMessageToHistory('system', `处理失败: ${data.error}`);
        }
    })
    .catch(error => {
        removeProcessingMessage(processingMessageId);
        addMessageToHistory('system', `处理出错: ${error}`);
    });
}

// 移除处理中的消息
function removeProcessingMessage(messageId) {
    const messageElement = document.getElementById(messageId);
    if (messageElement) {
        messageElement.remove();
    }
}

// 清空对话
function clearConversation() {
    const chatHistory = document.getElementById('chat-history');
    const thinkingIndicator = document.getElementById('ai-thinking');

    // 移除所有消息，但保留思考指示器
    while (chatHistory.firstChild !== thinkingIndicator) {
        chatHistory.removeChild(chatHistory.firstChild);
    }

    // 隐藏思考指示器
    thinkingIndicator.style.display = 'none';

    // 清空融合结果
    resultPreview.innerHTML = '<span>等待融合结果</span>';
    downloadBtn.style.display = 'none';
    clearImages();
//    alert('对话已清空');
}

// 下载结果
function downloadResult() {
    const formData = new FormData();
    formData.append('session_id', sessionId);

    fetch('/download_result', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (response.ok) {
            return response.blob();
        } else {
            return response.json().then(data => {
                throw new Error(data.error || '下载失败');
            });
        }
    })
    .then(blob => {
        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'fusion_result.png';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    })
    .catch(error => {
        alert('下载出错: ' + error.message);
    });
}

function addMessageToHistory(role, content) {
    const chatHistory = document.getElementById('chat-history');
    const thinkingIndicator = document.getElementById('ai-thinking');

    // 创建新消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = `chat-message ${role}`;

    const time = new Date().toLocaleTimeString();

    messageDiv.innerHTML = `
        <div class="message-header">
            <span>${role === 'user' ? '👤 您' : role === 'assistant' ? '🤖 AI助手' : '🔄 系统'}</span>
            <span class="message-time">${time}</span>
        </div>
        <div class="message-content">${content}</div>
    `;

    // 将消息插入到思考指示器之前
    chatHistory.insertBefore(messageDiv, thinkingIndicator);

    // 滚动到对话历史底部
    scrollToChatBottom();
}

// 更新对话历史
function updateChatHistory(history) {
    chatHistory.innerHTML = '';

    history.forEach(message => {
        if (message.role === 'user' || message.role === 'assistant') {
            addMessageToHistory(message.role, message.content);
        }
    });
}

function showThinking(show) {
    const thinkingIndicator = document.getElementById('ai-thinking');
    const sendBtn = document.getElementById('send-btn');
    const messageInput = document.getElementById('message-input');
    const clearBtn = document.getElementById('clear-btn');

    if (show) {
        thinkingIndicator.style.display = 'block';
        // 禁用相关按钮和输入框
        sendBtn.disabled = true;
        messageInput.disabled = true;
        clearBtn.disabled = true;

        // 添加禁用样式
        sendBtn.classList.add('disabled');
        messageInput.classList.add('disabled');
        clearBtn.classList.add('disabled');

        // 滚动到对话历史底部，确保思考指示器可见
        scrollToChatBottom();
    } else {
        thinkingIndicator.style.display = 'none';
        // 启用相关按钮和输入框
        sendBtn.disabled = false;
        messageInput.disabled = false;
        clearBtn.disabled = false;

        // 移除禁用样式
        sendBtn.classList.remove('disabled');
        messageInput.classList.remove('disabled');
        clearBtn.classList.remove('disabled');
    }
}

// 统一的UI更新函数
function updateUIWithResponse(data) {
    // 1. 隐藏思考指示器
    showThinking(false);

    if (data.success) {
        // 2. 显示AI回复
        addMessageToHistory('assistant', data.response);

        // 3. 更新快捷操作按钮状态（根据返回的图像数量）
        if (data.image_count !== undefined) {
            // 可以在这里更新按钮状态
        }

        // 4. 检查是否有处理结果
        if (data.result_image) {
            // 保存图像数据到全局变量，供下载使用
            window.lastResultImageData = data.result_image;

            // 显示图像
            resultPreview.innerHTML = `<img src="${data.result_image}" alt="处理结果">`;
            downloadBtn.style.display = 'block';
        }
    } else {
        alert('处理失败: ' + data.error);
    }
}

// 滚动到对话历史底部
function scrollToChatBottom() {
    const chatHistory = document.getElementById('chat-history');
    chatHistory.scrollTop = chatHistory.scrollHeight;
}